package com.isoft.controller;

import com.isoft.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.isoft.service.RandomDeviceDataService;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
@RequestMapping("/devices")
public class RandomDataController {
    private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    @Autowired
    private RandomDeviceDataService randomDeviceDataService;

    @Scheduled(fixedRate = 5000) // 每5秒钟执行一次
    public void sendDataToClients() {
        List<Device> randomDeviceData = randomDeviceDataService.generateRandomDeviceDataList(10);

        for (SseEmitter emitter : emitters) {
            try {
                emitter.send(SseEmitter.event().data(randomDeviceData));
            } catch (IOException e) {
                emitters.remove(emitter);
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/random")
    public SseEmitter streamRandomDeviceData() {
        SseEmitter emitter = new SseEmitter();
        emitters.add(emitter);

        // 设置超时处理
        emitter.onTimeout(() -> emitters.remove(emitter));

        // 设置连接关闭处理
        emitter.onCompletion(() -> emitters.remove(emitter));

        return emitter;
    }


}
